package services

import (
	"encoding/json"
	"math/rand"
	"os"
	"time"

	"homepage-backend/internal/models"
)

// LoadSites 从文件加载站点数据
func LoadSites(filePath string) ([]models.Site, error) {
	file, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}

	var sites []models.Site
	if err := json.Unmarshal(file, &sites); err != nil {
		return nil, err
	}

	return sites, nil
}

// GenerateSiteMap 生成网站地图
func GenerateSiteMap(sites []models.Site) models.SiteMap {
	var siteMapURLs []models.SiteMapURL
	for _, site := range sites {
		siteMapURLs = append(siteMapURLs, models.SiteMapURL{
			Loc:        site.URL,
			LastMod:    getRandomTimeWithinWeek().Format("2006-01-02"),
			ChangeFreq: "weekly",
			Priority:   "0.9",
		})
	}

	return models.SiteMap{
		XmlNS: "http://www.sitemaps.org/schemas/sitemap/0.9",
		URLs:  siteMapURLs,
	}
}

// getRandomTimeWithinWeek 返回一周之内的随机时间
func getRandomTimeWithinWeek() time.Time {
	now := time.Now()
	oneWeekAgo := now.AddDate(0, 0, -7)
	maxSeconds := int(now.Unix() - oneWeekAgo.Unix())
	randomSeconds := rand.Intn(maxSeconds)
	return oneWeekAgo.Add(time.Duration(randomSeconds) * time.Second)
}

// AddSite 添加新站点（自动生成唯一ID）
func AddSite(filePath string, site models.Site) error {
	if site.Name == "" {
		return nil // 不允许空title
	}
	sites, err := LoadSites(filePath)
	if err != nil {
		return err
	}
	// 如果前端未传id，则自动生成，使用同包的GenerateShortID
	if site.ID == "" {
		site.ID = GenerateShortID(site.Name + site.URL + time.Now().Format(time.RFC3339Nano))
	}
	sites = append(sites, site)
	return saveSites(filePath, sites)
}

// UpdateSite 修改站点（按ID匹配）
func UpdateSite(filePath string, site models.Site) error {
	if site.ID == "" {
		return nil
	}
	sites, err := LoadSites(filePath)
	if err != nil {
		return err
	}
	for i, s := range sites {
		if s.ID == site.ID {
			sites[i] = site
			return saveSites(filePath, sites)
		}
	}
	return nil // 未找到不报错
}

// DeleteSite 删除站点（按ID）
func DeleteSite(filePath string, id string) error {
	if id == "" {
		return nil
	}
	sites, err := LoadSites(filePath)
	if err != nil {
		return err
	}
	newSites := make([]models.Site, 0, len(sites))
	for _, s := range sites {
		if s.ID != id {
			newSites = append(newSites, s)
		}
	}
	return saveSites(filePath, newSites)
}

// saveSites 保存站点数据到文件
func saveSites(filePath string, sites []models.Site) error {
	data, err := json.MarshalIndent(sites, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(filePath, data, 0644)
}
